package cn.schoolwow.ams.test.module.common;

import cn.schoolwow.ams.module.block.listBlock.common.domain.operation.ListBlockRequest;
import cn.schoolwow.ams.test.entity.FlowLog;
import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.quickflow.flow.CompositeBusinessFlow;
import cn.schoolwow.quickflow.listener.FlowMappingHandler;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ExecuteFlowLogFlow implements BusinessFlow {
    @Autowired
    private QuickFlow testFlow;

    @Autowired
    private FlowMappingHandler testFlowMappingHandler;

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ListBlockRequest listBlockRequest = flowContext.checkInstanceData(ListBlockRequest.class);

        List<FlowLog> flowLogList = new ArrayList<>();
        if(null!=listBlockRequest.array){
            flowLogList.addAll(listBlockRequest.array.toJavaList(FlowLog.class));
        }else{
            flowLogList.add(listBlockRequest.row.toJavaObject(FlowLog.class));
        }
        for(FlowLog flowLog:flowLogList){
            CompositeBusinessFlow compositeBusinessFlow = testFlowMappingHandler.getCompositeBusinessFlow(flowLog.getName());
            JSONObject requestDataMap = flowLog.getRequestData();
            if(null!=compositeBusinessFlow){
                testFlow.startFlow(compositeBusinessFlow)
                        .putFlowContextDataMap(requestDataMap, FlowContextDataRange.Flow)
                        .execute();
            }else{
                BusinessFlow businessFlow = testFlowMappingHandler.getFlow(flowLog.getName());
                if(null!=businessFlow){
                    testFlow.startFlow(businessFlow)
                            .putFlowContextDataMap(requestDataMap, FlowContextDataRange.Flow)
                            .execute();
                }
            }
        }
    }

    @Override
    public String name() {
        return "执行流程日志";
    }
}
